<template>
	<!-- 通用版本 -->
	<view>
		<!-- 头部搜索框 -->
		<search :placeholder="$t('homepage.WarehouseManage.indicationNum')" />
		<!-- 查询结果列表 -->
		<view class="contain">
			<zy-table :headList="headList" :dataList="dataList" line @lineClick="lineClick" border></zy-table>
			<zy-button-group class="zy_btn_group">
				<zy-button @click="resetBtn" :disabled="disabled" type="danger"
					class="zy_btn">{{$t('public.reset')}}</zy-button>
				<zy-button @click="submitBtn" :disabled="disabled" type="primary" class="zy_btn">{{btnTxt}}</zy-button>
				<!-- <zy-button @click="storageBtn" :disabled="disabled" class="zy_btn">{{$t('homepage.WarehouseManage.staging'}}</zy-button> -->
			</zy-button-group>
		</view>
		<!-- 添加扫描弹窗 -->
		<zy-popup ref="zyPopup" :title="$t('homepage.WarehouseManage.boxSearch')" @confirm="submit">
			<zy-forms :model="model" labelWidth="80">
				<zy-form-item :label="$t('homepage.WarehouseManage.box')+$t('public.colon')">
					<zy-input v-model="model.boxNo" :placeholder="$t('homepage.WarehouseManage.box')"
						@confirm="codeConfirm" sufSlot>
						<i class="iconfont icon-saoyisao" @click="scanCode"></i>
					</zy-input>
				</zy-form-item>
			</zy-forms>
		</zy-popup>
		<!-- 获取暂存数据确认 -->
		<zy-popup ref="storagePopup" :title="$t('homepage.WarehouseManage.stagingConfirm')" type="dialog"
			@confirm="storageSubmitBtn">
			{{$t('homepage.WarehouseManage.continueGo')}}
		</zy-popup>
	</view>
</template>
<script>
	import {
		getOutInstructionsMainByNo,
		findBoxByMaterialCode,
		getStorehouseDetailByCode,
		saveStorehouseOut
	} from "@/api/homepage.js"
	import search from "@/components/topSearch/index.vue";
	import cardInfo from '../components/infoList.vue';
	export default {
		components: {
			search,
			cardInfo,
		},
		data() {
			return {
				iconfont: 'iconfont icon-saoyisao',
				fieldValue: '',
				//表格表头
				headList: [{
					name: this.$t('homepage.WarehouseManage.oldMaterialCode'),
					key: 'oldMaterialCode',
				}, {
					name: this.$t('homepage.WarehouseManage.materialCode'),
					key: 'materialCode',
				}, {
					name: this.$t('public.materialName'),
					key: 'materialName',
				}, {
					name: this.$t('public.num'),
					key: 'num',
				}, {
					name: this.$t('homepage.WarehouseManage.scanned'),
					key: 'scanNum',
				}],
				dataList: [], //表格数据
				btnTxt: this.$t('homepage.WarehouseManage.addScan'), //底部按钮名称
				disabled: true,
				//弹窗表单数据
				model: {
					boxNo: ''
				},
				//监听数组
				scanNumData: [],
				numData: [],
				orderId: '',
				scanDataList: [],
				dialogConfirmData: {},
				dialogCancelData: "",
				dialogScanDataList: [],
				getStorageDataShow: false,
			}
		},
		watch: {
			scanData: function(e) {
				//判断数量和已扫描数据是否相同
				if (e.scanNumData.length !== 0 && e.numData.length !== 0) {
					if (e.scanNumData.toString() == e.numData.toString()) {
						this.btnTxt = this.$t('public.submit')
					}
				}
			},
		},
		computed: {
			//监听表格扫描数量变化
			scanData() {
				this.scanNumData = []
				this.numData = []
				for (var i = 0; i < this.dataList.length; i++) {
					this.numData.push(this.dataList[i].num)
					this.scanNumData.push(this.dataList[i].scanNum)
				}
				return {
					scanNumData: this.scanNumData,
					numData: this.numData
				}
			}
		},
		onLoad() {
			this.getscancodedate()
		},
		onUnload() {
			// 移除监听事件      
			uni.$off('scancodedate')
			uni.$off('scancodepopdate')
		},
		methods: {
			//主页获取指示单号扫描事件
			getscancodedate() {
				// 移除监听“添加扫描”弹窗事件
				uni.$off('scancodepopdate')
				//PDA扫描主页指示单号
				var _this = this
				uni.$on('scancodedate', function(data) {
					_this.searchList(data.code)
				})
			},
			//“添加弹窗”获取扫描事件
			getscancodepopdate() {
				// 移除监听“指示单号”事件
				uni.$off('scancodedate')
				//PDA扫描“添加扫描”弹窗事件
				var _this = this
				uni.$on('scancodepopdate', function(data) {
					_this.model.boxNo = data.code
					_this.submit()
				})
			},
			searchList(e) {
				// if (uni.getStorageSync('deliveryData')) {
				// 	for (var i = 0; i < uni.getStorageSync('deliveryData').length; i++) {
				// 		if (uni.getStorageSync('deliveryData')[i].fieldValue == e) {
				// 			this.$refs.storagePopup.open()
				// 			this.dialogScanDataList = uni.getStorageSync('deliveryData')[i].scanDataList
				// 			this.dialogConfirmData = uni.getStorageSync('deliveryData')[i].dataList
				// 			this.orderId = uni.getStorageSync('deliveryData')[i].orderId
				// 			this.fieldValue = e
				// 		} else {
				// 			this.searchData(e)
				// 		}
				// 	}
				// } else {
				this.searchData(e)
				// }
			},
			// 获取暂存数据
			storageSubmitBtn() {
				this.$refs.storagePopup.close()
				this.getStorageDataShow = true
				this.scanDataList = this.dialogScanDataList
				this.dataList = this.dialogConfirmData
				this.orderId = this.orderId
				this.disabled = false
			},
			searchData(e) {
				this.fieldValue = e
				this.dataList = []
				getOutInstructionsMainByNo({
					billNo: e,
				}).then((res) => {
					console.log(res)
					if (res.code == 0) {
						this.orderId = res.data.id
						if (res.data.childList.length == 0) {
							uni.showToast({
								title: this.$t('public.noData'),
								icon: "none",
								duration: 3000
							})
						} else {
							//数组中每条对象添加已扫描字段scanNum:0
							res.data.childList.map((item, index) => {
								Object.assign(item, {
									scanNum: 0
								})
							})
							this.dataList = res.data.childList
							if (this.dataList) {
								this.disabled = false
							}
						}
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
					}
				}).catch((err) => {
					uni.showToast({
						title: err.message,
						icon: "none",
						duration: 3000
					})
				});
			},
			//表格点击行事件
			lineClick(e) {
				findBoxByMaterialCode({
					materialCode: e.value.materialCode,
				}).then((res) => {
					if (res.code == 0) {
						let data = encodeURIComponent(JSON.stringify(res.data));
						uni.navigateTo({
							url: './list?dataList=' + data,
						})
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
				});
			},
			// 重置页面
			resetBtn() {
				uni.redirectTo({
					url: "/HomePage/HomePage/WarehouseManage/ProductManagement/Outstorage/index"
				})
			},
			//底部按钮事件
			submitBtn: function() {
				this.model.boxNo = ''
				if (this.btnTxt == this.$t('homepage.WarehouseManage.addScan')) {
					this.$refs.zyPopup.open()
					this.getscancodepopdate()
				} else {
					saveStorehouseOut({
						billType: 1,
						applyDept: '',
						orderId: this.orderId,
						dataArray: JSON.stringify(this.scanDataList)
					}).then((res) => {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
						this.resetBtn()
					}).catch((res) => {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
					});
				}
			},
			// // 底部按钮"暂存"事件
			// storageBtn() {
			// 	if (!uni.getStorageSync('deliveryData')) {
			// 		let obj = {}
			// 		let arr = []
			// 		obj.fieldValue = this.fieldValue
			// 		obj.dataList = this.dataList
			// 		obj.scanDataList = this.scanDataList
			// 		obj.orderId = this.orderId
			// 		arr.push(obj)
			// 		uni.setStorageSync('deliveryData', arr);
			// 	} else {
			// 		let storageData1 = uni.getStorageSync('deliveryData')
			// 		for (var i = 0; i < storageData1.length; i++) {
			// 			if (storageData1[i].fieldValue == this.fieldValue) {
			// 				storageData1[i].dataList = this.dataList
			// 				storageData1[i].scanDataList = this.scanDataList
			// 				uni.setStorageSync('deliveryData', storageData1);
			// 			} else {
			// 				let storageData2 = uni.getStorageSync('deliveryData')
			// 				let obj = {}
			// 				obj.fieldValue = this.fieldValue
			// 				obj.dataList = this.dataList
			// 				obj.scanDataList = this.scanDataList
			// 				obj.orderId = this.orderId
			// 				storageData2.push(obj)
			// 				uni.setStorageSync('deliveryData', storageData2);
			// 			}
			// 		}
			// 	}
			// 	uni.redirectTo({
			// 		url: "/pages/HomePage/WarehouseManage/ProductManagement/GoodsDelivery/index"
			// 	})
			// 	uni.showToast({
			// 		title: this.$t('homepage.WarehouseManage.saveSuccess'),
			// 		icon: "none",
			// 		duration: 3000
			// 	})
			// },
			//弹窗编码扫描数据事件
			scanCode() {
				var mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module")
				mpaasScanModule.mpaasScan({
						// 扫码识别类型，参数可多选，qrCode、barCode，不设置，默认识别所有
						'scanType': ['qrCode', 'barCode'],
						// 是否隐藏相册，默认false不隐藏
						'hideAlbum': false
					},
					(ret) => {
						if (ret.resp_result) {
							this.model.boxNo = ret.resp_result;
							this.submit()
						}
					})
			},
			//添加扫描弹窗的键盘回车事件
			codeConfirm(e) {
				this.model.boxNo = e.value
				this.submit()
			},
			// 弹窗确定事件
			submit() {
				this.$refs.zyPopup.close()
				getStorehouseDetailByCode({
					code: this.model.boxNo,
				}).then((res) => {
					if (res.code == 0) {
						//判断箱号是否入库
						if (res.data.status == 1) {
							// 判断是否和"暂存"数据重复
							if (this.getStorageDataShow == true) {
								this.scanDataList = this.dialogScanDataList
							}
							//判断该箱号是否重复的扫描
							if (this.scanDataList.some(item => item.barcode === this.model.boxNo)) {
								uni.showToast({
									title: this.$t('public.searchRepeat'),
									icon: "none",
									duration: 3000
								})
							} else {
								this.model.boxNo = ''
								//判断扫描值是否配对this.dataList中物料编码值
								if (this.dataList.some(item => item.materialCode === res.data.materialCode)) {
									for (var i = 0; i < this.dataList.length; i++) {
										if (this.dataList[i].materialCode == res.data.materialCode) {
											if (this.dataList[i].scanNum < this.dataList[i].num) {
												this.dataList[i].scanNum = this.dataList[i].scanNum + res.data.num
												this.scanDataList.push(res.data)
											} else {
												uni.showToast({
													title: this.dataList[i].materialCode + this.$t(
															'public.max') + this.$t('public.colon') + this
														.dataList[i].num,
													icon: "none",
													duration: 3000
												})
											}
										}
									}
								} else {
									uni.showToast({
										title: this.$t('homepage.WarehouseManage.nullBoxNum'),
										icon: "none",
										duration: 3000
									})
								}
							}
						} else {
							uni.showToast({
								title: this.$t('homepage.WarehouseManage.boxDisInstorage'),
								icon: "none",
								duration: 3000
							})
							this.model.boxNo = ''
						}
					} else {
						uni.showToast({
							title: res.message,
							icon: "none",
							duration: 3000
						})
						this.model.boxNo = ''
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: "none",
						duration: 3000
					})
					this.model.boxNo = ''
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	.zy_btn_group {
		bottom: 0;
		position: fixed;
		width: 100%;

		.zy_btn {
			width: 50%;
		}
	}
</style>